#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os,sys
import glob
from dbproc.basedbproc import getConnect,initClientEncode

#===============================================================================
# 表 `prod_catagory` db proc
#===============================================================================

def updateProdCat(conn,selfCatId,catBaseId,id):
    ''' 更新各站点三级分类的对应的自有分类和所属大类别信息 '''
    curs = initClientEncode(conn)
    sqlStr = '''UPDATE `prod_catagory` SET `self_cat_id` = %s,
                                        `cat_base_id` = %s WHERE `prod_catagory`.`id` =%s '''
    param = (selfCatId,catBaseId,id)
    curs.execute(sqlStr, param)
    curs.close()

def seEncode(ustr, encoding='utf-8'):
    '''负责把入数据库的字符串，转化成utf-8编码'''
    if ustr is None:
        return ''
    if isinstance(ustr, unicode):
        return ustr.encode(encoding, 'ignore')
    elif isinstance(ustr, (list,tuple,set)):
        return '%s' % ','.join([seEncode(s,encoding) for s in ustr])        
    return str(ustr)

def exportSiteProdCat(site_id,level=3):
    conn = getConnect()
    curs = initClientEncode(conn)
    sqlStr = 'SELECT name, url, LEVEL FROM `prod_catagory` WHERE site_id =%s AND LEVEL =%s '  
    param = (site_id,level)
    curs.execute(sqlStr,param)
    result = curs.fetchall()
    curs.close()
    conn.close()
    return result
      
def buildCatDbMap():#有一个问题没有解决，对应的level 1 与level 2没有对应上分类
    curPath = os.path.abspath(os.path.dirname(sys.argv[0]))
    catBaseId = 1
    conn = getConnect()
    for f in glob.glob1(curPath, 'lusen.3C'):
        print f
        for line in file(f):
            line = line.strip()
            if line == '':
                continue
            ret = line.split('|')
            try:
                selfCatId = int(ret[-1])
            except ValueError:
                selfCatId = 0
                catBaseId = 0
            else:
                catBaseId = 1
            
            id = ret[-2]
            print selfCatId, catBaseId, id
            updateProdCat(conn, selfCatId, catBaseId, id)
    
    conn.close()

    
if __name__ == '__main__':
    #buildCatDbMap()
    f = file(r"c:\amazon.cat",'w')
    for t in exportSiteProdCat(site_id=1):
        s = seEncode(t)
        f.write(s)
        f.write(os.linesep)
    f.close()